--
-- DE2 (Cyclone-II) Entity for Interactive Project Game
-- Authors:
--      Abdulhamid Ghandour
--      Thomas John
--      Jaime Peretzman
--      Bharadwaj Vellore
--
-- Desc:
--

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity ci_pxl is
    port(
        clk             : in std_logic;
        mclk            : out std_logic; 	-- Master CLK to Camera
        lval            : in std_logic;     -- Line Valid from Camera
        fval            : in std_logic;     -- Frame Valid from Camera
        pixclk          : in std_logic;     -- Pixel CLK from Camera
        datain          : in unsigned(9 downto 0);    -- Pixel Data from Camera
        dataout         : out unsigned(9 downto 0);
        valid_green     : out std_logic;
        end_of_frame    : out std_logic;
        end_of_row      : out std_logic
   );
end ci_pxl;

architecture pool of ci_pxl is
    signal int_mclk : std_logic := '0';
    signal last_line_valid: std_logic := '0';
    signal last_frame_valid: std_logic := '0';
    signal pixel_counter: std_logic := '0';
    signal line_counter: std_logic:= '0';
    signal last_pixclk: std_logic := '0';
begin
    mclkgen : process(clk)
    begin
        if rising_edge(clk) then
            int_mclk <= not int_mclk;
        end if;
    end process;

    eor_gen : process(clk)
    begin
        if rising_edge(clk) then
            if (last_line_valid = '1' and lval = '0') then
                end_of_row <= '1';
                line_counter <= not line_counter;
            else
                end_of_row <= '0';
            end if;
            last_line_valid <= lval;
        end if;
    end process eor_gen;

    eof_gen : process(clk)
    begin
        if rising_edge(clk) then
            if (last_frame_valid = '1' and fval = '0') then
                end_of_frame <= '1';
            else
                end_of_frame <= '0';
            end if;
            last_frame_valid <= fval;
        end if;
    end process eof_gen;

    vg_gen : process(clk)
    begin
        if rising_edge(clk) then
            if (pixclk = '1' and last_pixclk = '0') then
                if lval = '1' then
                    pixel_counter <= not pixel_counter;
                    valid_green <= not (pixel_counter xor line_counter);
                    dataout <= datain;
                 end if;
            else
                valid_green <= '0';
            end if;
            last_pixclk <= pixclk;
		end if;
    end process vg_gen;
    
    mclk <= int_mclk;
end pool;
